package com.bii.gelapp;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MarkerCompareActivity extends Activity {
	Button btSave, btPrev, btGraph;
	ImageView ivImage;
	Bitmap originalBmp, activeBmp;
	public Bitmap colorBmp;
	ArrayList<ConnectedComponent> markerlist = new ArrayList<ConnectedComponent>();
	
	Bitmap bmap;
	Mat drawmat;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.markercompareactivity);
		ivImage = (ImageView)findViewById(R.id.ivImage);
		markerlist = (ArrayList<ConnectedComponent>) getIntent()
				.getSerializableExtra("markerlist");
		//colorBmp = MarkerGaborActivity.colorBmp;
		colorBmp = MarkerGaborActivity2.colorBmp;
		bmap = colorBmp;
		drawmat = new Mat(bmap.getHeight(), bmap.getWidth(), CvType.CV_8U);
		drawRectangles();
		
		ivImage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(),
						MarkerFullscreenActivity.class);
				byte[] bytes;
				
				bytes = compressImage(colorBmp);
				
				goToNextActivity.putExtra("BMP", bytes);
				goToNextActivity.putExtra("markerlist", markerlist);
				startActivity(goToNextActivity);
				
			}
		});
	}
	
	private void drawRectangles() {
		Utils.bitmapToMat(bmap, drawmat);
		for (int i = 0; i < markerlist.size(); i++) {
			Core.rectangle(
					drawmat,
					new Point(markerlist.get(i).left, markerlist
							.get(i).top),
					new Point(markerlist.get(i).right, markerlist
							.get(i).bottom), new Scalar(255, 255, 0), 2);
		}
		Bitmap drawnbmp = Bitmap.createBitmap(drawmat.cols(), drawmat.rows(),
				Bitmap.Config.RGB_565);
		Utils.matToBitmap(drawmat, drawnbmp);
		
		//Bitmap resizedbmp = Bitmap.createScaledBitmap(drawnbmp,
		//		300, 300, true);
		activeBmp = drawnbmp;
		ivImage.setImageBitmap(drawnbmp);

	};
	
	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;
	}
}
